import { ChromePicker } from 'react-color'
import { Popconfirm } from 'antd'
import React, { useState, useEffect } from 'react'

type PropsType = {
  value?: string
  defaultValue?: string
  onChange?: (color: string) => void
}

export function ColorPicker(props: PropsType) {
  const { onChange, value = '', defaultValue = '' } = props
  const [color, setColor] = useState<string>(defaultValue || value || '')
  const [cacheColor, setCacheColor] = useState<string>(
    defaultValue || value || ''
  )

  const onCacheChange = (color: any) => {
    if (color) {
      setCacheColor(color.hex)
    }
  }

  useEffect(() => {
    if (value) {
      setCacheColor(value)
    }
  }, [value])

  const onConfirm = (newColor: string) => {
    setColor(newColor)
    onChange?.(newColor)
  }

  return (
    <Popconfirm
      overlayClassName="colorPickerPopconfirm"
      icon=""
      onConfirm={() => {
        onConfirm(cacheColor)
      }}
      title={
        <ChromePicker color={cacheColor} onChangeComplete={onCacheChange} />
      }
    >
      <div
        style={{
          width: '80px',
          height: '30px',
          cursor: 'pointer',
          background: value || color,
          border: '1px solid #e7e6e6',
        }}
      ></div>
    </Popconfirm>
  )
}
